package com.lmxdawn.api;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.wxpay.sdk.WXPay;
import com.lmxdawn.api.dnf.dto.WxpayConfig;
import com.lmxdawn.api.im.handler.*;
import com.lmxdawn.api.im.service.LoginServiceProcessor;
import lombok.extern.slf4j.Slf4j;
import org.jim.core.packets.Command;
import org.jim.core.utils.PropUtil;
import org.jim.server.JimServer;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.ChatReqHandler;
import org.jim.server.command.handler.HandshakeReqHandler;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.config.ImServerConfig;
import org.jim.server.config.PropertyImServerConfigBuilder;
import org.jim.server.processor.chat.DefaultAsyncChatMessageProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.tio.core.ssl.SslConfig;

import java.util.concurrent.CompletableFuture;

@SpringBootApplication
@ServletComponentScan
@Slf4j
@Controller
@EnableScheduling
public class ApiAdminApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ApiAdminApplication.class, args);

        CompletableFuture.runAsync(()->{
            try {
                ImServerConfig imServerConfig = new PropertyImServerConfigBuilder("jim.properties").build();
                //初始化SSL;(开启SSL之前,你要保证你有SSL证书哦...)
    //        initSsl(imServerConfig);
                //设置群组监听器，非必须，根据需要自己选择性实现;
                imServerConfig.setImGroupListener(new ImDemoGroupListener());
                //设置绑定用户监听器，非必须，根据需要自己选择性实现;
                imServerConfig.setImUserListener(new ImDemoUserListener());
                JimServer jimServer = new JimServer(imServerConfig);

                /*****************start 以下处理器根据业务需要自行添加与扩展，每个Command都可以添加扩展,此处为demo中处理**********************************/

                HandshakeReqHandler handshakeReqHandler = CommandManager.getCommand(Command.COMMAND_HANDSHAKE_REQ, HandshakeReqHandler.class);
                //添加自定义握手处理器;
                handshakeReqHandler.addMultiProtocolProcessor(new DemoWsHandshakeProcessor());
                LoginReqHandler loginReqHandler = CommandManager.getCommand(Command.COMMAND_LOGIN_REQ,LoginReqHandler.class);
                //添加登录业务处理器;
                loginReqHandler.setSingleProcessor(new LoginServiceProcessor());
                //添加用户业务聊天记录处理器，用户自己继承抽象类BaseAsyncChatMessageProcessor即可，以下为内置默认的处理器！
                ChatReqHandler chatReqHandler = CommandManager.getCommand(Command.COMMAND_CHAT_REQ, ChatReqHandler.class);
                chatReqHandler.setSingleProcessor(new MessageProcessor());
//                CommandManager.registerCommand(new Notify24CmdHandler());
                /*****************end *******************************************************************************************/
                jimServer.start();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * 开启SSL之前，你要保证你有SSL证书哦！
     * @param imServerConfig
     * @throws Exception
     */
    private static void initSsl(ImServerConfig imServerConfig) throws Exception {
        //开启SSL
        if(ImServerConfig.ON.equals(imServerConfig.getIsSSL())){
            String keyStorePath = PropUtil.get("jim.key.store.path");
            String keyStoreFile = keyStorePath;
            String trustStoreFile = keyStorePath;
            String keyStorePwd = PropUtil.get("jim.key.store.pwd");
            if (StringUtils.isNotBlank(keyStoreFile) && StringUtils.isNotBlank(trustStoreFile)) {
                SslConfig sslConfig = SslConfig.forServer(keyStoreFile, trustStoreFile, keyStorePwd);
                imServerConfig.setSslConfig(sslConfig);
            }
        }
    }

    @Bean
    public WXPay wxPay(){
        try {
            return new WXPay(wxConfig());
        }catch (Exception e){
            log.error("init wxPay fail", e);
            return null;
        }
    }
    @Bean
    public WxpayConfig wxConfig(){
        try {
            return new WxpayConfig();
        }catch (Exception e){
            log.error("init wxPay fail", e);
            return null;
        }
    }


    @GetMapping("index")
    public String index() {
        return "index";
    }


    @PostMapping("createMenu")
    public void createMenu(){
        String json = "{\n" +
                "    \"button\": [\n" +
                "        {\n" +
                "            \"type\": \"view\",\n" +
                "            \"name\": \"我要购买\",\n" +
                "            \"url\": \"http://www.5808d.com/\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"type\": \"view\",\n" +
                "            \"name\": \"我要出售\",\n" +
                "            \"url\": \"http://www.5808d.com/sale\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"更多功能\",\n" +
                "            \"sub_button\": [\n" +
                "                {\n" +
                "                    \"type\": \"click\",\n" +
                "                    \"name\": \"购买比例\",\n" +
                "                    \"key\": \"buy\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"type\": \"click\",\n" +
                "                    \"name\": \"出售比例\",\n" +
                "                    \"key\": \"sale\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"type\": \"view\",\n" +
                "                    \"name\": \"个人中心\",\n" +
                "                    \"url\": \"http://www.5808d.com/person\"\n" +
                "                },\n" +
                "\n" +
                "                {\n" +
                "                    \"type\": \"click\",\n" +
                "                    \"name\": \"买卖辟邪玉\",\n" +
                "                    \"key\": \"bxy\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"type\": \"click\",\n" +
                "                    \"name\": \"问题反馈与投诉\",\n" +
                "                    \"key\": \"fk\"\n" +
                "                }\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}\n";

        String s = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx45dd9609efa0b1aa&secret=997c562963c7b5d4480a27e29c3cc6d2");
        log.info("===>{}", s);
        log.info(json);
        String token = JSON.parseObject(s).getString("access_token");
        String res = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token, json);
        log.info("createMenuRes: {}", res);

    }



}
